import 'package:badges/badges.dart';
import 'package:beautyflutter/componts/content_pager.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
class TabNatigator extends StatefulWidget {
  @override
  _TabNatigatorState createState() => _TabNatigatorState();
}

class _TabNatigatorState extends State<TabNatigator> {
  DateTime lastPopTime;
  final _defaultColor = Colors.grey;
  final _activeColor = Colors.blue;
  int _currentIndex = 0;
  final ContentPagerConteroller _contentPagerConteroller = ContentPagerConteroller();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: new WillPopScope(
        child: Container(
          decoration: BoxDecoration(
              gradient: LinearGradient(colors: [
                Color(0xffedeef0),
                Color(0xffe6e7e9)
              ],
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter)
          ),
          child: ContentPager(
            contentPagerConteroller: _contentPagerConteroller,
            onPageChanged: (int index) {
              setState(() {
                _currentIndex = index;
              });
            },
          ),
        ),
        onWillPop: () async {
          if(lastPopTime == null || (DateTime.now().difference(lastPopTime) > Duration(seconds: 1))){
            //两次点击间隔超过1秒，重新计时
            lastPopTime = DateTime.now();
            print(lastPopTime);
            showToast(
              "再按一次退出",
              duration: Duration(milliseconds: 2000),
              position: ToastPosition.bottom,
              backgroundColor: Colors.black.withOpacity(0.8),
              radius: 3.0,
              textStyle: TextStyle(fontSize: 18.0),
            );
            return false;
          }
          return true;
        }
      ),
      bottomNavigationBar: BottomNavigationBar(
        onTap: (index) {
          _contentPagerConteroller.jumpToPage(index);
          //修改状态
          this.setState(() {
            _currentIndex = index;
          });
        },
        type: BottomNavigationBarType.fixed,
        currentIndex: _currentIndex,
        items: [
          _bottomItem('本周', Icons.folder, 0),
          _bottomItem('分享', Icons.explore, 1),
          _bottomItem('免费', Icons.donut_small, 2),
          _bottomItem('长安', Icons.album, 3),
          _bottomItem('我的', Icons.person, 4),
        ],
      ),
    );
  }
  //封装底部tab
  _bottomItem(String title, IconData icon, int index) {
    return BottomNavigationBarItem(
      icon: Badge(
        showBadge: index == 2 ? true : false,
        child: Icon(icon, color: _defaultColor),
        badgeColor: Colors.red,
        badgeContent: Text('3', style: TextStyle(color: Colors.white)),
      ),
      activeIcon: Icon(icon, color: _activeColor),
      title: Text(
        title,
        style: TextStyle(color: _currentIndex != index ?_defaultColor:_activeColor)
      )
    );
  }
}
